from sqlalchemy import Integer, String, Boolean, DateTime, func, Table, Column, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base import Base
from datetime import datetime


# 用户角色关联表
user_role = Table(
    'user_role',
    Base.metadata,
    Column('user_id', String, ForeignKey('users.id'), primary_key=True),
    Column('role_id', String, ForeignKey('roles.id'), primary_key=True)
)

# 角色资源关联表
role_resource = Table(
    'role_resource',
    Base.metadata,
    Column('role_id', String, ForeignKey('roles.id'), primary_key=True),
    Column('resource_id', String, ForeignKey('resources.id'), primary_key=True),
    extend_existing=True
)


class Role(Base):
    __tablename__ = "roles"

    id: Mapped[str] = mapped_column(String(32), primary_key=True, index=True)
    tenant_id: Mapped[str] = mapped_column(String(32), ForeignKey("tenants.id"), nullable=True)
    name: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=False)
    description: Mapped[str] = mapped_column(String(255), nullable=True)
    created_user:  Mapped[str] = mapped_column(String(32))
    created_at: Mapped[DateTime] = mapped_column(DateTime, default=datetime.utcnow)
    updated_at: Mapped[DateTime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 添加与用户的多对多关系
    users: Mapped[list["User"]] = relationship(
        "User",
        secondary=user_role,
        back_populates="roles",
        lazy="selectin"
    )
    
    # 添加与资源的多对多关系
    resources: Mapped[list["Resource"]] = relationship(
        "Resource",
        secondary=role_resource,
        back_populates="roles",
        lazy="selectin"
    )

    def __repr__(self):
        return f"<Role(id='{self.id}', name='{self.name}', description='{self.description}')>"